const db = uniCloud.database()
const dbCmd = db.command;
const uniID = require('uni-id')
module.exports = {
	main: async (event) => {
		let {
			res,
			data,
			action
		} = event;
		switch (action) {
			case 'query':
				res.data = await getData(data);
				break;
			case 'queryById':
				res.data = await getDataById(data);
				break;
			case 'queryByTime':
				res.data = await getDataByTime(data);
				break;
			case 'queryOne':
				res.data = await getCountBystate(data);
				break;
			case 'add':
				res = await addData(data);
				break;
			case 'edit':
				res = await editData(data);
				break;
			case 'del':
				res = await delData(data);
				break;
			default:
				res = {
					code: 402,
					msg: '非法访问'
				}
				break;
		}
		return res;
	}
}
/**
 * 获取列表数据
 */
async function getData(data) {
	
	const result = await db.collection('order')
		.where({
			state: data.state == 0 ? dbCmd.neq('null') : data.state,
			userId: data.userId,
			outTradeNo: eval('/' + data.outTradeNo + '/'),
		})
		.skip(data.offset)
		.limit(data.limit==undefined?10:data.limit)
		.orderBy('createtime', 'desc')
		.get()
	return result.data
}
/**
 * 获取数据通过ID
 */
async function getDataById(data) {
	var result = await db.collection('order').doc(data.id).get()
	return result.data
}
/**
 * 获取数据通过TIME
 */
async function getDataByTime(data) {
	const result = await db.collection('order')
		.where({
			state: data.state==''? dbCmd.neq('null') : data.state,
			outTradeNo: eval('/' + data.outTradeNo + '/'),
			timestampCT: dbCmd.gte(Date.parse(data.startDate)-28800000).and(dbCmd.lte(Date.parse(data.endDate) + 86400000 - 28800000))
		})
		.skip((data.page-1)*data.limit)
		.limit(data.limit)
		.orderBy('createtime', 'desc')
		.get()
	const resultTotal = await db.collection('order')
		.where({
			state: data.state==''? dbCmd.neq('null') : data.state,
			outTradeNo: eval('/' + data.outTradeNo + '/'),
			timestampCT: dbCmd.gte(Date.parse(data.startDate)-28800000).and(dbCmd.lte(Date.parse(data.endDate) + 86400000 - 28800000))
		})
		.count()
	
	let res = {
		total:resultTotal.total,
		records:result.data
	}
	return res
}
/**
 * @param {Object} data
 */
async function getCountBystate(data) {
	const result = await db.collection('order').where({
		state: data.state,
		userId: data.userId
	}).count()
	return result.total
}
/**
 * 添加数据
 */
async function addData(data) {
	var res = {}
	const result = await db.collection('order').add({
		commentState: 1,
		serviceState: 1,
		discountAmount: data.discountAmount,
		shippingMod: data.shippingMod,
		desc: data.desc,
		outTradeNo: data.outTradeNo,
		totalExpress: data.totalExpress,
		userId: data.userId,
		state: 1,
		stateTip: '待付款',
		pointToMoney: data.pointToMoney,
		goodsPrice: data.goodsPrice,
		totalPrice: data.totalPrice,
		goodsData: data.goodsData,
		addressData: data.addressData,
		selectedCoupon: data.selectedCoupon,
		payment_channel: '',
		transactionId:'',
		timestampCT: data.timestamp,
		createtime: data.createtime
	})
	res.data = result
	//更新优惠券
	if (JSON.stringify(data.selectedCoupon) != "{}") {
		const result2 = await db.collection('coupon_user').doc(data.selectedCoupon.couponUserId).update({
			state: 1,
			updatetime: data.updatetime
		})
	}
	//更新库存  更新销量
	let mData = data.goodsData;
	for (let i = 0; i < mData.length; i++) {
		const r1 = await db.collection('goods').doc(mData[i].proId).get();
		const r2 = await db.collection('goods').doc(mData[i].proId).update({
			saleNum: r1.data[0].saleNum + mData[i].number
		})

		if (mData[i].attr_val == '') { //说明没有规格
			const r3 = await db.collection('goods').doc(mData[i].proId).update({
				proData: {
					skuStock: (parseInt(r1.data[0].proData.skuStock) - parseInt(mData[i].number))
				}
			})
		} else {
			let tmpSkuDetailArray = r1.data[0].proData.skuDetailArray;
			for (let j = 0; j < tmpSkuDetailArray.length; j++) {
				if (tmpSkuDetailArray[j].name == mData[i].attr_val) {
					tmpSkuDetailArray[j].stock = parseInt(tmpSkuDetailArray[j].stock) - mData[i].number
					break;
				}
			}
			const r4 = await db.collection('goods').doc(mData[i].proId).update({
				proData: {
					skuDetailArray: tmpSkuDetailArray,
					skuStock: (parseInt(r1.data[0].proData.skuStock) - parseInt(mData[i].number))
				}
			})
		}
	}
	
	//更新用户最后一次下单时间
	const resT = await uniID.updateUser({
	    uid: data.userId,
	    last_buy_date: data.timestamp
	  })
	res.code = 200;
	return res;
}
/**
 * 更新数据
 */
async function editData(data) {
	var res = {}
	const result = await db.collection('order').doc(data.id).update({
		state: data.state,
		stateTip: getStateTip(data)
	})
	res.code = 200;
	res.data = result.data
	return res;
}
/**
 * @param {Object} data
 * 删除数据
 */
async function delData(data) {
	var res = {}
	var tmp = await db.collection('order').doc(data.id).remove()
	if (tmp.deleted === 1) {
		res.code = 200
		res.msg = '删除成功'
	} else {
		res.code = 402
		res.msg = '删除失败'
	}
	return res
}

async function getStateTip(data) {
	let stateTip = ''
	if (data.state == 1) {
		stateTip = '待付款';
	} else if (data.state == 2) {
		stateTip = '待发货';
	} else if (data.state == 3) {
		stateTip = '待收货';
	} else if (data.state == 4) {
		stateTip = '待提货';
	} else if (data.state == 5) {
		stateTip = '待成团';
	} else if (data.state == 10) {
		stateTip = '已完成';
	} else if (data.state == -1) {
		stateTip = '已取消';
	} else if (data.state == -2) {
		stateTip = '已关闭';
	}
	return stateTip;
}
